package com.wonderplay.engine;

import android.graphics.Canvas;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

//logicEngine should be run in another thread
public abstract class LogicEngine {

	protected GameEngine gameEngine;
	protected int moduleId;
	protected ModuleChangeNotifier moduleChangeNotifier;
	
	public LogicEngine(GameEngine gameEngine, int moduleId){
		this.gameEngine = gameEngine;
		this.moduleId = moduleId;
		moduleChangeNotifier = new ModuleChangeNotifier(moduleId);
	}
	
	public void doStep(){
		SurfaceHolder surfaceHolder = gameEngine.getSurfaceHolder();
		Canvas canvas = null;

		try {
			canvas = surfaceHolder.lockCanvas();
			synchronized (surfaceHolder) {
				updateLogic();
				drawCanvas(canvas);
				if (moduleChangeNotifier.isValid == true) {
					sendModuleChangeReq(moduleChangeNotifier.sendModule,
							moduleChangeNotifier.changeCode,
							moduleChangeNotifier.message);
					moduleChangeNotifier.reset();
				}
			}
		} finally {
			// do this in a finally so that if an exception is thrown
			// during the above, we don't leave the Surface in an
			// inconsistent state
			if (canvas != null) {
				surfaceHolder.unlockCanvasAndPost(canvas);
			}
		}
	}

	public abstract void updateLogic();
	
	public abstract void performKeyEvent(KeyEvent keyEvent);
	
	public abstract void performTouchEvent(MotionEvent touchEvent);

	public abstract void drawCanvas(Canvas canvas);

	public abstract void reset();
	
	public void init(){
		
	}
	
	protected void sendModuleChangeReq(int sendModule, int changeCode,
			ModuleChangeMessage message){
		if (gameEngine != null){
			gameEngine.onModuleChangeReq(sendModule, changeCode, message);
		}
	}
}
